// pages/canvas/canvas.js
const io = require('../../utils/weapp.socket.io.js');
const api = require("../../config.js");

let socket = null;



Page({

	ctx:null,
	type:null,
	/**
	 * 页面的初始数据
	 */
	data: {
		headimg:"",
		nick_name:"",
		color:"#000000",
		color_style:"display:inline-block;width:1em;height:1em;border-radius:0.3em;box-shadow:1px 1px 2px #000;background:#000;",
		bi_style:"display:inline-block;width:0.4em;height:0.4em;background:#000;border-radius:1em;box-shadow:1px 1px 2px #000;",
		LineWidth:3,
		scrollTop:0,
		users:[],
		chats:[],
		is_disabled:true,
		input_placeholder:"",
		progress:100,
		answer:'',
		is_to_draw:false,
		cofirm_dialog_content:"轮到你了",
		input_value:""
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.type = options.type;
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		
		//链接wss
		this.createConnect();
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {
		this.disconnect();
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		this.disconnect();
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
	
	},

	//游戏开始 (针对绘画者)
	gameStart(){
		let cofirm_dialog = this.selectComponent('#cofirm_dialog');
		cofirm_dialog.show();
	},

	//断开链接
	disconnect(){
		if(!this.socket){
			return false;
		}
		//断开链接
		this.socket.disconnect();
		this.socket = null;
	},

	canvasIdErrorCallback: function (e) {
		console.error(e.detail.errMsg)
	},
	onReady: function (e) {
		// 使用 wx.createContext 获取绘图上下文 context
		this.ctx = wx.createCanvasContext('drawcanvas');
	},

	canvas_obj:[],//保存路径的动画

	touchstart:function(e){
		if (!this.data.is_to_draw)return false;
		let touch = e.changedTouches[0];
		//this.ctx.moveTo(touch.x, touch.y);
		//提交
		this.socket.emit("someOneDraw",{type:"moveTo",x:touch.x,y:touch.y});
	},

	touchmove:function(e){
		if (!this.data.is_to_draw) return false;
		let touch = e.changedTouches[0];
		// this.ctx.setLineCap('round');
		// this.ctx.setLineJoin('round');
		// this.ctx.setLineWidth(this.data.LineWidth);
		// this.ctx.setStrokeStyle(this.data.color);
		// this.ctx.lineTo(touch.x, touch.y);
		// this.ctx.stroke();
		// this.ctx.draw(true);
		// this.ctx.moveTo(touch.x, touch.y);

		this.socket.emit("someOneDraw", { type: "lineTo", x: touch.x, y: touch.y, setLineWidth: this.data.LineWidth, setStrokeStyle: this.data.color});
		this.socket.emit("someOneDraw",{type:"draw"});
		this.socket.emit("someOneDraw", { type: "moveTo", x: touch.x, y: touch.y});
	},
	touchend(){
		if (!this.is_to_draw) return false;
	},

	empty:function(){
		//清空
		this.ctx.clearRect(0,0,200,200);
		this.ctx.draw();
		//发送消息
		socket.emit("someOneDraw",{type:"clean"});
	},

	//滑块
	sliderchange:function(e){
		let value = e.detail.value;
		let v = parseFloat(value/5).toFixed(1) + "em";
		let a = parseInt(value);
		this.data.bi_style += "width:"+v+";height:"+v+";";
		this.setData({ bi_style: this.data.bi_style, LineWidth:a});
	},

	//选择颜色
	changeColor:function(e){
		let color = e.target.dataset.color;
		this.data.color_style += "background:"+color+";";
		this.data.bi_style += "background:" + color + ";";
		this.setData({ color_style: this.data.color_style, color: color, bi_style: this.data.bi_style});
	},

	//提交表单
	commit:function(e){
		let value = e.detail.value;
		socket.emit("answer",value);
		this.setData({
			input_value:""
		});
		//this.createOneMsg("success",value," 正确");
	},

	createOneMsg:function(type,first,last,t){
		let icon = "warning";
		let color = "#bbbbbb";
		if(type == "info"){
			icon = "warning";
			color = "#007af8";
		}else if(type == "success"){
			icon = "yes";
			color = "#16a846";
		}else if(type == "danger"){
			icon = "no";
			color = "#ee191d";
		}
		let data = {
			icon: icon,//yes,warning,
			color: color,//红色#ee191d   #007af8 蓝色  #16a846绿色
			name: first,
			content: " "+last,
			type: (t?true:false)
		};
		let chats = this.data.chats;
		chats.push(data);
		this.setData({ chats });
		let self = this;
		wx.createSelectorQuery().select('#scroll_chat').fields({
			dataset: true,
			size: true,
			scrollOffset: true,
			properties: ['scrollX', 'scrollY']
		}, function (res) {
			self.setData({ scrollTop: res.height });
		}).exec();
	},

	settest(e){
		this.add_core(0,10);
	},

	//游戏开始点击确定,
	cofirm_dialog_onConfirm(){
		let cofirm_dialog = this.selectComponent('#cofirm_dialog');
		cofirm_dialog.hide();
		socket.emit("ok",{});
		this.setData({
			is_disabled: true,
			is_to_draw:true,
			input_placeholder: "绘画中...",
			input_value:""
		});
	},
	//游戏开始点击跳过
	cofirm_dialog_onCancel(){
		let cofirm_dialog = this.selectComponent('#cofirm_dialog');
		cofirm_dialog.hide();
		socket.emit("skip", JSON.parse(wx.getStorageSync('userInfo')));
	},

	//给某个人加分
	add_core(user_index,score){
		var animation = wx.createAnimation({
			duration: 1300,
			timingFunction: 'ease',
			transformOrigin: "50% 50%",
		});
		this.data.users[user_index].score = score;
		this.setData({ users: this.data.users });
		this.data.users[user_index].animationData = animation.opacity(0).top(-20).step().export();
		this.setData({ users: this.data.users });
		setTimeout(() => {
			this.data.users[user_index].num += this.data.users[user_index].score;
			this.data.users[user_index].score = 0;
			this.setData({ users: this.data.users });
		}, 1300)
	},


	createConnect:function(){
		if (this.socket){
			return false;
		}
		//return false;
		socket = (this.socket = io(
			api.socket_api
		));
		socket.on('connect', () => {
			let user_info = JSON.parse(wx.getStorageSync('userInfo'));
			user_info.type = ["fast"];
			user_info = JSON.stringify(user_info);
			this.socket.emit("root_room", user_info);
		});

		//有人加入
		socket.on("someOneJoin",(res)=>{
			this.createOneMsg("info", res.nick_name, "刚刚加入了房间");
			this.data.users.push(res);
			this.setData({ users: this.data.users});
		});

		//监听其他人绘画
		socket.on("otherDraw",(res)=>{
			if(res.type == "moveTo"){
				this.ctx.moveTo(res.x, res.y);
			} else if (res.type == "lineTo"){
				this.ctx.setLineCap('round');
				this.ctx.setLineJoin('round');
				this.ctx.setLineWidth(res.setLineWidth);
				this.ctx.setStrokeStyle(res.setStrokeStyle);
				this.ctx.lineTo(res.x,res.y);
			}else if(res.type == "draw"){
				this.ctx.stroke();
				this.ctx.draw(true);
			}else if(res.type == "clean"){
				//清空
				this.ctx.clearRect(0, 0, 200, 200);
				this.ctx.draw();
			}
		});

		//答题之后
		socket.on("afterAnswer",(res)=>{
			//判断是否答对
			if(res.type == 1){
				//答对了
				this.createOneMsg("success","恭喜你","答对了",false);
				this.setData({ is_disabled:true });
			}else if(res.type == 0){
				//答错了
				this.createOneMsg("warning","我:",res.answer,false);
			}
		});

		//其他人回答
		socket.on("afterAnswer_other",res=>{
			if(res.type == 1){
				//答对了
				this.createOneMsg("success",res.userInfo.nick_name,"答对了",false);
			}else if(res.type == 0){
				this.createOneMsg("warning", res.userInfo.nick_name,res.answer,false);
			}
		});

		//其他人该选择了
		socket.on("ortherTurn",res=>{
			wx.showToast({
				title:"轮到"+res.nick_name+"画"
			});
			this.setData({
				is_to_draw: false
			});
		});

		//加入之后
		socket.on("afterLogin",(res)=>{
			this.init(res);
		});


		//监听读秒
		socket.on("status",(res)=>{
			//同步进度条
			this.setData({
				progress: res.progress,
			});
			//判断游戏状态
			if(res.status == 2){
				//将所有东西都归为初始化
				this.empty();
				this.setData({
					is_disabled: true,
					input_placeholder: "",
					input_value:"",
					is_to_draw:false
				});
			}
		});	

		//监听时间长没选择而跳过游戏
		socket.on("skip_game",(res)=>{
			let cofirm_dialog = this.selectComponent('#cofirm_dialog');
			cofirm_dialog.hide();
			let user_info = wx.getStorageSync("userInfo");
			user_info = JSON.parse(user_info);
			if (res.openid != user_info.openid){
				wx.showToast({
					title: res.nick_name + '选择跳过',
					icon: 'none',
					duration: 1500
				});
			}
		});
		//轮到你了
		socket.on("youTurn",(res)=>{
			this.setData({
				//input_placeholder:"轮到你了",
				is_disabled:true,
				cofirm_dialog_content:"轮到你了,请画出 '"+res.answer+"' 来"
			});
			this.gameStart();
		});

		//游戏开始
		socket.on("game_start",(res)=>{
			this.setData({
				input_placeholder: "填写答案",
				input_value:"",
				is_disabled: false,
				is_to_draw:false
			});
		});

		//公布答案
		socket.on("say_answer",(res)=>{
			let str = "";
			if(res.type == "all"){
				str = "所有人都答对了!";
			}else{
				str = "正确答案是:'" + res.answer + "'";
			}
			if (!this.data.is_to_draw){
				wx.showToast({
					title: str,
					duration: 2500
				});
			}else{
				wx.showToast({
					title: "所有人都答对了,这轮游戏已结束",
					duration: 2500
				});
			}
		});

		//加分
		socket.on("addCore",(res)=>{
			for(let i=0;i<this.data.users.length;i++){
				if (this.data.users[i].openid == res.userInfo.openid){
					this.add_core(i,res.num);
				}
			}
		});

		//有人离开
		socket.on("someOneLeave",(res)=>{
			this.createOneMsg("danger", res.nick_name, "刚刚离开了房间");
			//循环users列表
			for(let i=0;i<this.data.users.length;i++){
				if (this.data.users[i].nick_name == res.nick_name){
					this.data.users.splice(i, 1);
					this.setData({ users: this.data.users });
					break;
				}
			}
		});
	},

	//解析初始化数据
	init(data){
		let user_info = JSON.parse(wx.getStorageSync('userInfo'));
		
		if(data.status == 0){
			//游戏尚未开始
			wx.showToast({
				title: '暂时没有人,请耐心等待',
				icon: 'none',
				duration: 2000
			});
		}
		//同步用户
		//同步聊天信息  (只同步最近10个聊天信息)
		let chats = data.chats.slice(-10);
		//同步进度条
		
		this.setData({ users: data.users, chats: chats, progress: data.progress});

		this.createOneMsg("info", "你刚刚", "加入房间");
		
		//同步画布
		for(let i=0;i<data.canvas.length;i++){
			let res = data.canvas[i];
			if (res.type == "moveTo") {
				this.ctx.moveTo(res.x, res.y);
			} else if (res.type == "lineTo") {
				this.ctx.setLineCap('round');
				this.ctx.setLineJoin('round');
				this.ctx.setLineWidth(res.setLineWidth);
				this.ctx.setStrokeStyle(res.setStrokeStyle);
				this.ctx.lineTo(res.x, res.y);
			} else if (res.type == "draw") {
				this.ctx.stroke();
				this.ctx.draw(true);
			} else if (res.type == "clean") {
				//清空
				this.ctx.clearRect(0, 0, 200, 200);
				this.ctx.draw();
			}
		}
	},
});